package visitor

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/visitor"
	visitorReq "github.com/flipped-aurora/gin-vue-admin/server/model/visitor/request"
)

type VisitService struct {
}

// CreateVisit 创建visit表记录
// Author [piexlmax](https://github.com/piexlmax)
func (visitService *VisitService) CreateVisit(visit *visitor.Visit) (err error) {
	err = global.GVA_DB.Create(visit).Error
	return err
}

// DeleteVisit 删除visit表记录
// Author [piexlmax](https://github.com/piexlmax)
func (visitService *VisitService) DeleteVisit(visit visitor.Visit) (err error) {
	err = global.GVA_DB.Delete(&visit).Error
	return err
}

// DeleteVisitByIds 批量删除visit表记录
// Author [piexlmax](https://github.com/piexlmax)
func (visitService *VisitService) DeleteVisitByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]visitor.Visit{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateVisit 更新visit表记录
// Author [piexlmax](https://github.com/piexlmax)
func (visitService *VisitService) UpdateVisit(visit visitor.Visit) (err error) {
	err = global.GVA_DB.Save(&visit).Error
	return err
}

// GetVisit 根据id获取visit表记录
// Author [piexlmax](https://github.com/piexlmax)
func (visitService *VisitService) GetVisit(id uint) (visit visitor.Visit, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&visit).Error
	return
}

// GetVisitInfoList 分页获取visit表记录
// Author [piexlmax](https://github.com/piexlmax)
func (visitService *VisitService) GetVisitInfoList(info visitorReq.VisitSearch) (list []visitor.Visit, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&visitor.Visit{})
	var visits []visitor.Visit
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	//根据姓名查询
	if info.Username != "" {
		db = db.Where("username like ?", "%"+info.Username+"%")
	}
	//根据公司查询
	if info.Company != "" {
		db = db.Where("company like ?", "%"+info.Company+"%")
	}
	//根据通行方式查询
	if info.Passway != nil {
		sexBool := *info.Passway
		sexInfo := 0
		if sexBool {
			sexInfo = 1
		}
		db = db.Where("passway =?", sexInfo)
	}
	//根据设备类型查询
	if info.Device != "" {
		db = db.Where("device like ?", "%"+info.Device+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&visits).Error
	return visits, total, err
}
